import router from "@/router";
import {
	mapState
} from "vuex";
import {
	host
} from "@/store/axiosConfig.js"; //导入 axios 配置
import waves from '@/directives/waves/index.js' // 水波纹指令
export default {
	directives: {
		waves
	},
	data() {
		return {
			genderMap: {
				1: '男',
				2: '女'
			},
			demo: 'https://picsum.photos/300/300',
			//上传接口字段
			upload_col_name: "file",
			//上传相关
			upload_image: `${host}/api/upload`,
			upload_video: `${host}/api/uploadFile`,
			// paging_layout: 'total,prev, pager, next,jumper',
			paging_layout: 'total,sizes,prev,pager,next,jumper',
			mixViewportWidth: 1920

		};
	},
	computed: {
		...mapState(["webConfig", "baseInfo", "is_login", 'shop_id']),
		uploadExtraData() {
			let data = {
				token: localStorage.getItem("token") || "",
			};
			return data;
		},
		mix_isps() {
			let ps = [21, 22, 12, 11]
			if (ps.indexOf(this.baseInfo.role) != -1) {
				return true;
			}
			if (this.baseInfo.is_expert == 1) {
				return true;
			}
			return false;
		},


	},

	created() {},
	mounted() {},
	destroyed() {},
	methods: {
		openUrl(url) {
			if (url) {
				window.open(url)
			}
		},
		getFileName(url) {
			if (url) {
				return url.split('/').pop();
			}
		},
		mix_filterArr(data, key) {
			let arr = data[key];
			if (Array.isArray(arr) && arr.length) {
				return arr.map((v) => {
					if (Array.isArray(v) && v.length == 0) {
						return {};
					} else {
						return v;
					}
				});
			} else {
				return [{}];
			}
		},
		mix_isNull_1(str) {
			if (typeof str == 'number') {
				if (str == 0) return false;
			} else {
				if (str == 0) return false;
				if (str == '' || str == null || str == undefined) return true;
			}
		},
		mix_notNull(obj, key) {
			let val = obj[key]
			// if (val == null) return false;
			if (val && Array.isArray(val) && val.length > 0) {
				return true;
			}

			if (typeof val == 'string') {
				if (val != '') {
					return true;
				}
			}
			return false;
		},


		mix_splitStr(str, flag = ',') {
			if (str) {
				let arr = str.split(',');
				return arr.join(flag)
			}
			return '';
		},
		mix_isInc(item, arr) {},

		mix_xz(name) {
			let l = this.mix_getOptions('attachment');
			let item = l.find((v) => v.title == name) || {};
			if (item.file) {
				let str = item.file;
				let lastIndex = str.lastIndexOf("/");
				// 使用 substring 方法截取最后一个斜杠后面的内容
				let result = str.substring(lastIndex + 1);
				const extension = item.file.split('.').pop();
				this.mix_downloadFile(item.file, `${name}${extension}`);
			}
		},
		mix_isNumeric(input) {
			return !isNaN(input) && !isNaN(parseFloat(input));
		},
		mix_downloadFile(url, fileName) {
			fetch(url)
				.then((response) => response.blob())
				.then((blob) => {
					const blobUrl = URL.createObjectURL(blob);
					const link = document.createElement('a');
					link.href = blobUrl;
					link.download = fileName;
					link.click();
					URL.revokeObjectURL(blobUrl);
				})
				.catch((error) => {
					console.error('文件下载失败', error);
					window.open(url)
				});
		},
		mix_getOptions(key) {
			let item = this.mix_dictData.find(v => v.slug == key) || {};
			return item.value || [];
		},
		mix_setImageAfter(url) {
			// if (process.env.NODE_ENV == "production") {
			// 	if (!url.includes(location.protocol)) return `${location.protocol}//${url}`;
			// } else {
			// 	if (!url.includes('https:')) return `https://${url}`;
			// }
			return url;
		},

		mix_createFilter(queryString) {
			return (restaurant) => {
				return restaurant.value.toLowerCase().includes(queryString.toLowerCase());
			};
		},
		mix_setTableHeader(headers = [], table_labels = []) {
			let arr = headers.map((name) => {
				let item = table_labels.find((v) => v.label == name);

				return item;
			}).filter(Boolean);

			return arr;
		},

		mix_getIndex(name, arr) {
			let index = arr.findIndex((item) => item.label == name)
			return index;
		},


		mix_deepCopy(source) {
			if (!typeof source === 'object' && source !== null) return source //如果不是对象的话直接返回
			let target = Array.isArray(source) ? [] : {} //数组兼容
			for (let k in source) {
				if (source.hasOwnProperty(k)) {
					if (typeof source[k] === 'object') {
						target[k] = this.mix_deepCopy(source[k])
					} else {
						target[k] = source[k]
					}
				}
			}
			return target
		},


		mix_setNavPath(key = 'id', value, route) {
			this.$router.replace({
				path: route || this.$route.path,
				query: {
					...this.$route.query,
					[key]: value,
				}
			});
		},
		mix_getAgreementById(id) {
			let obj = this.webConfig.agreement_list.find(v => v.id == id) || {};
			return obj;
		},
		mix_setImage(img) {
			if (img) {
				// return require('@img/qiugou01.png');
				return require(`@img/${img}`);

			}
		},



		getAgreement(id, key = 'title') {
			if (this.webConfig.agreement_list) {
				let obj = this.webConfig.agreement_list.find(v => v.id == id) || {};
				return obj[key]
			}
		},
		deepCloneArray(arr) {
			let clone = [];
			for (let i = 0; i < arr.length; i++) {
				if (Array.isArray(arr[i])) {
					clone[i] = deepCloneArray(arr[i]);
				} else {
					clone[i] = arr[i];
				}
			}
			return clone;
		},

		mix_setRoutePath(key, value) {
			this.$nextTick(() => {
				let params = new URLSearchParams(`${this.$route.fullPath}`);
				if (!this.$route.fullPath.includes(key)) {
					if (!params.has(key)) {
						if (this.$route.fullPath.includes('?')) {
							params.append(key, value);
							let path = params.toString();
							history.replaceState({}, '', decodeURIComponent(path));
							// this.toNav(decodeURIComponent(path));
						} else {
							history.replaceState({}, '', `${this.$route.fullPath}?${key}=${value}`);
							// this.toNav(`${this.$route.fullPath}?${key}=${value}`);
						}
					}
				}

			})
		},





		mix_setAddressStr(data) {
			return data;
			if (this.region_list.length) {
				let item = this.region_list.find((v) => v.code == data) || {};
				if (!item.code) {
					return data;
				}
				return item.short_name;
			}
		},


		setListBylist(arr, level = 0, result = []) {
			for (let i = 0; i < arr.length; i++) {
				let item = arr[i];
				if (level > 1) {
					this.$set(item, 'disabled', true);
				}
				result.push(item);
				if (item['children'] && item['children'].length > 0) {
					this.setListBylist(item['children'], level + 1);
				}
			}
			return result;
		},
		mix_logout() {
			this.$store.commit("clear_loginInfo");
			alertSucc("已退出登陆");
			this.toNav(`/login`)
		},
		mix_userinfo_query() {
			this.$store.dispatch("getUserInfo");
		},

		toNav(route) {
			if (route[0] == '/') {
				this.$router.push(route)
			} else {
				this.$router.push('/' + route)
			}
		},
		toRep(route) {
			if (route[0] == '/') {
				this.$router.replace(route)
			} else {
				this.$router.replace('/' + route)
			}

		},
		toBack() {
			this.$router.back();
		},
		toLink(item) {
			if (item.url) {
				location.href = item.url;
			} else {
				item && window.open(item)
			}
		},







		//上传文件
		mix_fileUpload(params) {

			const formData = new FormData();
			formData.append("action", "index_upload");
			formData.append("com_id", this.com_id);
			formData.append("user_id", localStorage.getItem("user_id"));
			formData.append("token", localStorage.getItem("token"));
			formData.append("img", params.file);
			formData.append("if_touxiang", params.if_touxiang || "");

			const uploaderConfig = {
				headers: {
					"Content-Type": "multipart/form-data;boundary=" + new Date().getTime(),
				},
			};
			return this.$api("index_upload", formData, "post", uploaderConfig);
		},


		getInpVal(key, mode = 'localStorage') {
			let loc = JSON.parse(window['localStorage'].getItem(`input_${key}`)) || [];
			let ses = JSON.parse(window['sessionStorage'].getItem(`input_${key}`)) || [];
			let newArray = loc.concat(ses);
			return newArray;
		},
		setInputVal(val, key, mode = 'localStorage') {
			if (!val) return;
			let value = {
				value: val
			};
			let loc = JSON.parse(window[mode].getItem(`input_${key}`));
			if (loc && Array.isArray(loc)) {
				if (!loc.find((v) => v.value == val)) {
					window[mode].setItem(`input_${key}`, JSON.stringify(loc.concat(value)));
				}
			} else {
				window[mode].setItem(`input_${key}`, JSON.stringify([value]));
			}
		},


		mix_generateRandomString(length) {
			let result = '';
			const characters = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
			const charactersLength = characters.length;
			for (let i = 0; i < length; i++) {
				result += characters.charAt(Math.floor(Math.random() * charactersLength));
			}
			return result;
		},
	}
};